<template>
    <div>
      <a-descriptions bordered>
        <a-descriptions-item label="头像">
          <div style="display: flex;align-items: center;flex-direction: column;gap: 6px">
            <a-image
                :width="62"
                v-if="!workerInfo.profilePicture && workerInfo.sex == 0"
                :src="boy"
            />
            <a-image
                :width="62"
                v-else-if="!workerInfo.profilePicture && workerInfo.sex == 1"
                :src="girl"
            />
            <a-image
                :width="62"
                v-else
                style="border-radius: 50%"
                :src=" proxy.PicPrefixUrl + workerInfo.profilePicture"
            />
            <span style="opacity: 0.6;font-weight: bolder">{{ workerInfo.name }}</span>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="账号状态" >
          <a-badge status="processing" text="正常" v-if="workerInfo.isActive == 0" />
          <a-badge status="error" text="禁用" v-if="workerInfo.isActive == 1" />
        </a-descriptions-item>
        <a-descriptions-item label="电子邮箱" >
          {{ workerInfo.email }}
        </a-descriptions-item>
        <a-descriptions-item label="姓名" :span="1">{{ workerInfo.realName }}</a-descriptions-item>
        <a-descriptions-item label="性别" :span="0.5">
          <a-tag color="#f0a1a8" v-if="workerInfo.sex == 1">女</a-tag>
          <a-tag color="#108ee9" v-if="workerInfo.sex == 0">男</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="身份证" :span="1.5">{{ workerInfo.idCard }}</a-descriptions-item>
        <a-descriptions-item label="联系电话" >
          {{ workerInfo.phoneNumber ? workerInfo.phoneNumber : '' }}
        </a-descriptions-item>
        <a-descriptions-item label="紧急联系人姓名">
          {{ workerInfo.emergencyContactName ? workerInfo.emergencyContactName : '' }}
        </a-descriptions-item>
        <a-descriptions-item label="紧急联系人电话">
          {{ workerInfo.emergencyContactPhoneNumber ? workerInfo.emergencyContactPhoneNumber : '' }}
        </a-descriptions-item>
        <a-descriptions-item label="毕业院校">{{ workerInfo.graduatedFrom }}</a-descriptions-item>
        <a-descriptions-item label="学历">{{ workerInfo.education }}</a-descriptions-item>
        <a-descriptions-item label="专业">{{ workerInfo.major }}</a-descriptions-item>
        <a-descriptions-item label="入职时间" :span="1">
          {{ dayjs(workerInfo.joinDate).format('YYYY-MM-DD') }}
        </a-descriptions-item>
        <a-descriptions-item label="合同结束" :span="1">
          {{dayjs(workerInfo.contractExpiryDate).format('YYYY-MM-DD')}}
        </a-descriptions-item>
        <a-descriptions-item label="合同描述" :span="1">
          {{ workerInfo.contractPeriod }}
        </a-descriptions-item>
      </a-descriptions>
      <a-space class="submit">
        <a-button @click="()=> { router.go(-1) }">返回上级</a-button>
        <a-button type="primary" @click="editEvent">修改资料</a-button>
        <a-button type="primary" danger @click="()=> { pwdStore.open = true }">修改密码</a-button>
        <a-dropdown>
          <button class="exploreBts">
            探索功能
          </button>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="()=> { router.push('/other/auntsAssistant') }">
                <DotChartOutlined />
                <a class="operationItem">姨妈助手</a>
              </a-menu-item>
              <a-divider class="divider" />
            </a-menu>
          </template>
        </a-dropdown>
      </a-space>

      <a-modal
          v-model:open="editStore.open"
          title="修改个人信息"
          width="730px"
          @cancel="cancel"
          @ok="submit"
      >
        <a-form
            style="margin: 12px 0"
            :model="editStore.worker"
            labelAlign="right"
            ref="infoFrom"
            :rules="rules"
            :label-col="{ style: { width: '80px' } }"
        >
          <div>
            <a-form-item label="头像" name="profilePicture">
              <a-upload
                  name="file"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  :action="proxy.UploadUrl"
                  @change="handleUpload"
              >
                <div v-if="editStore.worker.profilePicture">
                  <img :src="proxy.PicPrefixUrl + editStore.worker.profilePicture"  alt="avatar" class="iconPre" />
                </div>
                <div v-else>
                  <loading-outlined v-if="loading"></loading-outlined>
                  <plus-outlined v-else></plus-outlined>
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </div>
          <a-row :gutter="[16,16]">
            <a-col :span="12">
              <a-form-item label="姓名" name="realName">
                <a-input v-model:value="editStore.worker.realName" placeholder="请输入真实姓名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="身份证" name="idCard">
                <a-input v-model:value="editStore.worker.idCard" placeholder="请输入身份证号码" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[16,16]">
            <a-col :span="8">
              <a-form-item label="性别" name="sex">
                <a-radio-group v-model:value="editStore.worker.sex">
                  <a-radio :value="0">男</a-radio>
                  <a-radio :value="1">女</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="学历" name="education">
                <a-input v-model:value="editStore.worker.education" placeholder="请输入学历" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="专业" name="major">
                <a-input v-model:value="editStore.worker.major" placeholder="请输入专业" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[16,16]">
            <a-col :span="12">
              <a-form-item label="毕业院校" name="graduatedFrom">
                <a-input v-model:value="editStore.worker.graduatedFrom" placeholder="请输入毕业院校" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="邮箱" name="email">
                <a-input v-model:value="editStore.worker.email" placeholder="请输入电子邮箱" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[16,16]">
            <a-col :span="12">
              <a-form-item label="用户名" name="name">
                <a-input v-model:value="editStore.worker.name" placeholder="请输入用户名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="手机号码" name="phoneNumber">
                <a-input v-model:value="editStore.worker.phoneNumber" placeholder="请输入手机号码" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[16,16]">
            <a-col :span="12">
              <a-form-item label="紧急人" name="emergencyContactName">
                <a-input v-model:value="editStore.worker.emergencyContactName" placeholder="请输入紧急联系人" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="电话" name="emergencyContactPhoneNumber">
                <a-input v-model:value="editStore.worker.emergencyContactPhoneNumber" placeholder="请输入紧急联系人电话" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-modal>

      <a-modal
          v-model:open="pwdStore.open"
          title="修改密码"
          width="500px"
          @cancel="cancelPwd"
          @ok="submitPwd"
      >
        <a-form
            style="margin: 12px 0"
            :model="pwdStore.req"
            labelAlign="right"
            ref="pwdFrom"
            :rules="pwdRules"
            :label-col="{ style: { width: '80px' } }"
        >
          <a-form-item label="旧密码" name="oldPwd">
            <a-input-password type="password" v-model:value="pwdStore.req.oldPwd" placeholder="请输入旧密码"  />
          </a-form-item>
          <a-form-item label="新密码" name="newPwd">
            <a-input-password v-model:value="pwdStore.req.newPwd" placeholder="请输入新密码" />
          </a-form-item>
          <a-form-item label="确认密码" name="confirmPwd">
            <a-input-password v-model:value="pwdStore.req.confirmPwd" placeholder="请输入确认密码" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
</template>

<script setup lang="ts">
    import boy from "@/assets/img/boy.png";
    import girl from "@/assets/img/girl.png";
    import dayjs from "dayjs";
    import {getCurrentInstance, onMounted, ref} from "vue";
    import { useLoginStore } from "@/stores/loginStore";
    import type {User} from "@/interface/User";
    import  { oneIdApi , updatePersonalInfoApi , changePwdApi } from "@/controller/UserApi";
    import {message, type UploadChangeParam} from "ant-design-vue";
    import { LoadingOutlined, PlusOutlined , DotChartOutlined } from "@ant-design/icons-vue";
    import { useRouter } from "vue-router";

    const router = useRouter();

    const loginStore = useLoginStore();
    const { proxy } = getCurrentInstance() as any;

    let workerInfo = ref({} as User);
    let loading = ref(false);
    onMounted(() => {
      getWorkerInfo();
    });

    const handleUpload = (info: UploadChangeParam) => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        if(info.file.response.code == 200) {
          workerInfo.value.profilePicture = info.file.response.data;
          loading.value = false;
        }else {
          message.error("文件上传失败!");
          loading.value = false;
        }
      }
    };

    let pwdRules = {
      oldPwd: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
      ],
      newPwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
      ],
      confirmPwd: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { validator: async (rule: any, value: string, callback: any) => {
            if (value !== pwdStore.value.req.newPwd) {
              return Promise.reject('两次输入密码不一致!');
            }else {
              return Promise.resolve();
            }
          }
        }
      ]
    }
    function cancelPwd() {
      pwdStore.value.open = false;
      pwdStore.value.req = {
        userId: loginStore.loginInfo.user.user.id,
        oldPwd: "",
        newPwd: "",
        confirmPwd: ""
      }
    }

    function submitPwd() {
      pwdFrom.value.validate().then( () => {
        changePwdApi({ userId : loginStore.loginInfo.user.user.id , oldPwd : pwdStore.value.req.oldPwd, newPwd : pwdStore.value.req.newPwd }).then( res => {
          if (res.code === 200) {
            message.success("修改成功!");
            loginStore.loginOut();
          } else {
            message.error(res.msg);
          }
        });
      }).catch((err : any) => {
        console.log(err);
      });
    }

    function getWorkerInfo() {
      if (loginStore.loginInfo.user && loginStore.loginInfo.user.user.id) {
          oneIdApi(loginStore.loginInfo.user.user.id).then( res => {
            if (res.code === 200) {
              workerInfo.value = res.data;
            }
          });
      }
    }

    let infoFrom = ref();

    let rules = {
      realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      idCard: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' }
      ],
      phoneNumber: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入电子邮箱', trigger: 'blur' }
      ],
      emergencyContactName: [
        { required: true, message: '请输入紧急联系人', trigger: 'blur' }
      ],
      emergencyContactPhoneNumber: [
        { required: true, message: '请输入紧急联系人电话', trigger: 'blur' }
      ],
      sex: [
        { required: true, message: '请选择性别', trigger: 'blur' }
      ],
      education: [
        { required: true, message: '请输入学历', trigger: 'blur' }
      ],
      major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
      ],
      graduatedFrom: [
        { required: true, message: '请输入毕业院校', trigger: 'blur' }
      ],
      birthday: [
        { required: true, message: '请输入出生日期', trigger: 'blur' }
      ]
    }
    let editStore = ref({
      open :  false,
      worker: {} as User
    });

    let pwdFrom = ref();
    let pwdStore = ref({
      open : false,
      req : {
        userId: '',
        oldPwd : '',
        newPwd : '',
        confirmPwd : ''
      }
    });


    function editEvent() {
      editStore.value.worker = workerInfo.value;
      editStore.value.open = true;
    }

    function cancel() {
      editStore.value.open = false;
      getWorkerInfo();
    }

    function submit() {
      infoFrom.value.validate().then(() => {
        updatePersonalInfoApi(editStore.value.worker).then( res => {
            if (res.code === 200) {
              message.success('更新成功');
              getWorkerInfo();
              editStore.value.open = false;
            }else {
              message.error("更新失败");
            }
        });
      }).catch((err : any) => {
        console.log(err);
      })
  }

</script>

<style scoped lang="scss">
    .operationItem {
      margin-left: 6px !important;
    }
    .divider {
      margin: 0 !important;
    }
    .submit {
      margin-top: 18px;
      display: flex;
      justify-content: center;
    }
    .iconPre {
      height: 100px;
      width: 100px;
      border-radius: 8px;
    }
    .exploreBts {
      background-color: rebeccapurple;
      box-shadow: 0 2px 0 rgba(255, 38, 5, 0.06);
      color: #FFFFFF;
      height: 32px;
      padding: 4px 15px;
      border-radius: 6px;
      border: none;
      cursor: pointer
    }
</style>
